package com.sgb.kjwl.view.ui.fragment.material;

import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;

import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentMaterialList4Binding;
import com.sgb.kjwl.di.material.DaggerMaterialFragComponent;
import com.sgb.kjwl.di.material.MaterialFragModule;
import com.sgb.kjwl.model.entity.SearchMaterialEntity3;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.LeaseEvent;
import com.sgb.link.event.MaterialEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.material.GoodsAggregateActivity;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopGoodsDetailActivity;
import com.sgb.kjwl.view.ui.adapter.search.SearchMaterialAdapter3;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.MaterialFliterPopWindow3;
import com.sgb.kjwl.viewmodel.material.MaterialListFragModel4;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import javax.inject.Inject;

/**
 * Description: 商品筛选列表改版4
 * Author cfk
 */
public class MaterialListFragment4 extends AppFragment {
    public static String KEY_ID = "id";
    public static String KEY_FID = "fId";
    public static String KEY_TYPE_Id = "typeId";
    public static String KEY_NAME_Id = "nameId";
    public static String KEY_POSITION = "position";
    @Inject
    MaterialListFragModel4 viewModel;
    private FragmentMaterialList4Binding binding;
    private SearchMaterialAdapter3 adapter;
    private String id;//全部商品
    private String fId;//一级
    private String typeId;//二级分类
    private int position;
    private String lon;
    private String lat;
    private DictWindow5 nameWindow5;
    private String nameId = "";//品名
    private List<DictEntity3> nameDictEntityList;
    private DictWindow5 storeMultiWindow4;
    private List<DictEntity3> storeDictEntityList;
    private String areaId = "";
    private DictWindow5 distanceWindow5;
    private String distanceId = "";
    private List<DictEntity3> distanceDictEntityList;
    private MaterialFliterPopWindow3 popWindow;
    private List<DictEntity3> typeDictEntityList;
    private List<DictEntity3> priceDictEntityList;
    private AllMaterialListFragment3 allMaterialListFragment3;
    private boolean isCreate = false;
    private boolean init = true;
    private boolean isVisible;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                adapter.setDatas(null);
                init();
            }
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof GoodsAggregateActivity) {
            GoodsAggregateActivity activity = (GoodsAggregateActivity) context;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreate = true;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMaterialFragComponent.builder()
                .appComponent(appComponent)
                .materialFragModule(new MaterialFragModule(this))
                .build()
                .inject(this);
    }

    public static MaterialListFragment4 newInstance(String id, String fId, String typeId, String nameId, int position, int type) {
        MaterialListFragment4 fragment = new MaterialListFragment4();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_ID, id);
        bundle.putString(KEY_FID, fId);
        bundle.putString(KEY_TYPE_Id, typeId);
        bundle.putString(KEY_NAME_Id, nameId);
        bundle.putInt(KEY_POSITION, position);
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_material_list4, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        id = getArguments().getString(KEY_ID);
        fId = getArguments().getString(KEY_FID);
        typeId = getArguments().getString(KEY_TYPE_Id);
        position = getArguments().getInt(KEY_POSITION);
        int type = getArguments().getInt("type");
        nameId = getArguments().getString(KEY_NAME_Id);
        viewModel.type.set(type);
        if (getParentFragment() instanceof AllMaterialListFragment3) {
            allMaterialListFragment3 = (AllMaterialListFragment3) getParentFragment();
        }
        initView();
        if (init && isVisible) {
            init = false;
            adapter.setDatas(null);
            init();
        }
    }

    private void initView() {
        binding.nameArrowView.setOnClickListener(this);
        binding.storeArrowView.setOnClickListener(this);
        binding.distanceArrowView.setOnClickListener(this);
        binding.tvLoc.setOnClickListener(this);
//        binding.imgShopCar.setOnClickListener(this);
        binding.screen.setOnClickListener(this);
        binding.imgBackTop.setOnClickListener(this);
        adapter = new SearchMaterialAdapter3(getActivity(), null);
        adapter.setDatas(null);

        adapter.setOnItemClick(new AdapterOnItemClick<SearchMaterialEntity3>() {
            @Override
            public void onItemClick(SearchMaterialEntity3 searchMaterialEntity, int position) {
                ShopGoodsDetailActivity.start(getActivity(), searchMaterialEntity.getId(), "", searchMaterialEntity.getSkuid());
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));

        binding.recyclerView.setAdapter(adapter);

        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getMaterialModel(false);
            }

            @Override
            public void onLoadMore() {
                viewModel.getMaterialModel(true);
            }
        });
        if (position == 0) {
            binding.layoutBar.setVisibility(View.GONE);
        } else {
            binding.layoutBar.setVisibility(View.VISIBLE);
        }
        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (layoutManager.findFirstVisibleItemPosition() > 0) {
                    binding.imgBackTop.setVisibility(View.VISIBLE);
                } else {
                    binding.imgBackTop.setVisibility(View.GONE);
                }
            }
        });


        initFilterView();
    }

    private void initFilterView() {
        nameWindow5 = new DictWindow5(getActivity());
        nameWindow5.setOnCallBack(dictEntity -> {
            nameId = dictEntity.getId();
            viewModel.materialFilterJson.get().setItemId(dictEntity.getId());
            viewModel.getMaterialModel(false);
            popWindow.setNameDefault(nameWindow5.getCheckDefultPosition(dictEntity.getId()), dictEntity.getId());
            popWindow.setBrandDefault(-1, null);
        });
        nameWindow5.setOnCloseBack(() -> setTextViewBg(binding.nameArrowView, R.drawable.corner999_f5f5f5_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333));
        storeMultiWindow4 = new DictWindow5(getActivity());
        storeMultiWindow4.setOnCallBack(dictEntity -> {
            areaId = dictEntity.getId();
            viewModel.materialFilterJson.get().setAreaId(dictEntity.getId());
            viewModel.getMaterialModel(false);
            popWindow.setAreaDefault(storeMultiWindow4.getCheckDefultPosition(dictEntity.getId()), dictEntity.getId());
        });

        storeMultiWindow4.setOnCloseBack(() -> setTextViewBg(binding.storeArrowView, R.drawable.corner999_f5f5f5_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333));
        distanceWindow5 = new DictWindow5(getActivity(), 1);
        distanceWindow5.setOnCallBack(dictEntity -> {
            distanceId = dictEntity.getId();
            viewModel.materialFilterJson.get().setDistance(dictEntity.getName());
            viewModel.getMaterialModel(false);
            popWindow.setDistanceDefault(distanceWindow5.getCheckDefultPosition(dictEntity.getId()), dictEntity.getId());
        });
        distanceWindow5.setOnCloseBack(() -> setTextViewBg(binding.distanceArrowView, R.drawable.corner999_f5f5f5_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333));
        popWindow = new MaterialFliterPopWindow3(getActivity());
        popWindow.setBgView(binding.grayLayout);
        popWindow.setFilterResultClick(new MaterialFliterPopWindow3.FilterResultClick() {
            @Override
            public void result(MaterialFilterJson materialFilterJson, List<DictEntity3> data, SparseBooleanArray checkBooleanArray) {
                viewModel.materialFilterJson.get().setAreaId(materialFilterJson.getAreaId());
                viewModel.materialFilterJson.get().setBrandId(materialFilterJson.getBrandId());
                viewModel.materialFilterJson.get().setCategoryId(materialFilterJson.getCategoryId());
                viewModel.materialFilterJson.get().setItemId(materialFilterJson.getItemId());
                viewModel.materialFilterJson.get().setMaterValue(materialFilterJson.getMaterValue());
                viewModel.materialFilterJson.get().setDistance(materialFilterJson.getDistance());
                viewModel.materialFilterJson.get().setPriceSort(materialFilterJson.getPriceSort());
                viewModel.getMaterialModel(false);
                typeId = materialFilterJson.getCategoryId();
                allMaterialListFragment3.changeType(getCheckTypeDefultPosition(typeId));

                nameId = materialFilterJson.getItemId();
                nameWindow5.setCheckDefaultById(nameWindow5.getCheckDefultId(nameId));

                distanceId = materialFilterJson.getDistance();
                distanceWindow5.setCheckDefaultById(distanceWindow5.getCheckDefultId(distanceId));

                areaId = materialFilterJson.getAreaId();
                storeMultiWindow4.setCheckDefaultById(storeMultiWindow4.getCheckDefultId(areaId));
            }

            @Override
            public void queryTypeChild(String id) {
                viewModel.getFilterNameModel(id, false);
            }

            @Override
            public void queryNameChild(String id) {
                viewModel.getFilterBrandModel(id);
                viewModel.getFilterBrandSpec(id);
            }
        });

        popWindow.setOnDisMissClick(() -> EventBus.getDefault().post(LeaseEvent.make().setMessageTag(EventConstant.EVENT_SHOP_VISIBLE)));
    }

    private void init() {
        viewModel.areaCode.set(viewModel.getAreaCodeModel());
        if (id.equals("0")) {
            viewModel.materialFilterJson.get().setCid1(fId);
        } else {
            viewModel.materialFilterJson.get().setCid3(id);
        }
        viewModel.materialFilterJson.get().setCategoryId(typeId);
        viewModel.materialFilterJson.get().setItemId(nameId);
        viewModel.getMaterialModel(false);
    }

    public void setCurrentItem(String id, String fId, String nameId, String typeId, int position) {
        this.nameId = nameId;
        this.id = id;
        this.typeId = typeId;
        this.fId = fId;
        if (position == 0) {
            binding.layoutBar.setVisibility(View.GONE);
        } else {
            binding.layoutBar.setVisibility(View.VISIBLE);
        }
        init();
    }

    public void showList(List<SearchMaterialEntity3> list, boolean isLoadMore) {
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() != 0) {
                adapter.addDatas(list);
            }
        } else {
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }
            binding.recyclerView.refreshComplete();
            binding.recyclerView.setLoadingMoreEnabled(true);
            adapter.setDatas(list);
        }
    }

    public void showNamePopWindow(List<DictEntity3> data, boolean isShowPop) {
        this.nameDictEntityList = data;
        if (data == null || data.size() == 0) {
            viewModel.getMaterialModel(false);
            return;
        }
        if (isShowPop) {
            nameWindow5.setData(data);
            nameWindow5.showPopwindow(binding.nameArrowView);
            nameWindow5.setCheckDefaultById(nameId);
        }
        viewModel.materialFilterJson.get().setItemId(nameId);
        popWindow.setNameData(data);
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getId().equals(nameId)) {
                popWindow.setNameDefault(i, nameId);
            }
        }
        viewModel.getFilterBrandModel(nameId);
        viewModel.getFilterBrandSpec(nameId);
        viewModel.getMaterialModel(false);
        if (nameId == null || nameId.equals("")) {
            nameWindow5.setCheckDefaultByName("全部");
        }
    }

    public void showStorePopWindow(List<DictEntity3> data, boolean isShowPop) {
        this.storeDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }
        if (isShowPop) {
            storeMultiWindow4.setData(data);
            storeMultiWindow4.showPopwindow(binding.storeArrowView);
        }
        popWindow.setAreaData(data);
        if (TextUtils.isEmpty(areaId)) {
            storeMultiWindow4.setCheckDefaultByName("全部");
        }
    }

    public void showDistancePopWindow(List<DictEntity3> data, boolean isShowPop) {
        this.distanceDictEntityList = data;
        if (data == null || data.size() == 0) {
            Toast.makeText(getActivity(), "该商品分类暂未配置距离筛选值", Toast.LENGTH_SHORT).show();
            return;
        }
        distanceWindow5.setData(data);
        if (isShowPop) {
            distanceWindow5.showPopwindow(binding.distanceArrowView);
        }
        popWindow.setDistanceData(data);
        if (TextUtils.isEmpty(distanceId)) {
            distanceWindow5.setCheckDefaultByName("全部");
        }
    }

    public void showPop(List<DictEntity3> data) {
        this.distanceDictEntityList = data;
        popWindow.setDistanceData(data);
        distanceWindow5.setData(data);
    }

    public void showTypePopWindow(List<DictEntity3> data) {
        this.typeDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }
        if (typeId == null || typeId.equals("")) {
            typeId = data.get(0).getId();
        }
        viewModel.getFilterNameModel(typeId, false);
        popWindow.setTypeData(data);
        popWindow.setTypeDefault(position, typeId);
    }

    public void showPricePopWindow(List<DictEntity3> data) {
        this.priceDictEntityList = data;
        if (data == null || data.size() == 0) {
            return;
        }
        popWindow.setPriceData(data);
    }

    public void showBrandPopWindow(List<DictEntity3> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        popWindow.setBrandData(data);
    }

    public void showFilterBrandSpec(List<DictEntity3> data) {
        if (data == null) {
            return;
        }
        popWindow.setSpecData(data);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.name_arrow_view:
                setTextViewBg(binding.nameArrowView, R.drawable.search_new_blue_bg, R.mipmap.pick_select_up_normal, R.color.new_blue);
                if (nameDictEntityList == null) {
                    viewModel.getFilterNameModel(typeId, true);
                } else {
                    nameWindow5.setData(nameDictEntityList);
                    nameWindow5.showPopwindow(binding.nameArrowView);
                    nameWindow5.setCheckDefaultById(nameId);
                }
                break;
            case R.id.store_arrow_view:
                setTextViewBg(binding.storeArrowView, R.drawable.search_new_blue_bg, R.mipmap.pick_select_up_normal, R.color.new_blue);
                if (storeDictEntityList == null) {
                    viewModel.getFilterStoreModel(true);
                } else {
                    storeMultiWindow4.showPopwindow(binding.storeArrowView);
                    storeMultiWindow4.setData(storeDictEntityList);
                    storeMultiWindow4.setCheckDefaultById(areaId);
                }
                break;
            case R.id.distance_arrow_view:
                setTextViewBg(binding.distanceArrowView, R.drawable.search_new_blue_bg, R.mipmap.pick_select_up_normal, R.color.new_blue);
                if (distanceDictEntityList == null || distanceDictEntityList.size() == 0) {
                    viewModel.getFilterDistance(fId, 0);
                } else {
                    distanceWindow5.showPopwindow(binding.distanceArrowView);
                    distanceWindow5.setData(distanceDictEntityList);
                    distanceWindow5.setCheckDefaultById(distanceId);
                }
                break;
            case R.id.screen:
                EventBus.getDefault().post(LeaseEvent.make().setMessageTag(EventConstant.EVENT_SHOP_GONE));
                popWindow.setTypeDefault(position, typeId);
                popWindow.showListVisible(position);
                popWindow.showPopwindowRight((GoodsAggregateActivity.getPopView()));
                if (storeDictEntityList == null) {
                    viewModel.getFilterStoreModel(false);
                }
                if (typeDictEntityList == null) {
                    viewModel.getFilterTypeModel(fId);
                }
                if (distanceDictEntityList == null || distanceDictEntityList.size() == 0) {
                    viewModel.getFilterDistance(fId, 1);
                }
                if (priceDictEntityList == null) {
                    viewModel.getFilterPrice();
                }
                break;
            case R.id.tv_loc:
                if (TextUtils.isEmpty(lat) || TextUtils.isEmpty(lon)) {
                    MToast.showToast(getContext(), "您未开启定位服务，无法使用定位功能");
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getActivity(), SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "选择定位地址");
                intent.putExtra(SelectAddressActivity.LATITUDE, Double.valueOf(lat));
                intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.valueOf(lon));
                startActivityForResult(intent, 102);
                break;
            case R.id.img_back_top:
                binding.recyclerView.smoothScrollToPosition(0);
                break;
        }

    }

    private int getCheckTypeDefultPosition(String checkedId) {
        if (typeDictEntityList == null || typeDictEntityList.size() == 0) {
            return -1;
        }
        for (int i = 0; i < typeDictEntityList.size(); i++) {
            if (typeDictEntityList.get(i).getId().equals(checkedId)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 102 && data != null) {
            lat = String.valueOf(data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0));
            lon = String.valueOf(data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0));
            viewModel.getMaterialModel(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MaterialEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MATERIAL_FILTER) {
            String text = (String) event.getMessageData();
            viewModel.materialFilterJson.get().setText(text);
            viewModel.getMaterialModel(false);
        } else if (event.getMessageTag() == EventConstant.EVENT_GOODS_LOC) {
            lon = (String) event.getObject();
            lat = (String) event.getMessageData();
            viewModel.materialFilterJson.get().setLat(lat);
            viewModel.materialFilterJson.get().setLon(lon);
        }
    }

    private void setTextViewBg(TextView textView, int bg, int img, int textColor) {
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());  //此为必须写的
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

    private void setDrwImage(TextView tv, int type) {
        Drawable img_off;
        Resources res = getResources();
        if (type == 0) {
            img_off = res.getDrawable(R.mipmap.icon_up_red);
        } else {
            img_off = res.getDrawable(R.mipmap.icon_down_red);
        }
        img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
        tv.setCompoundDrawables(null, null, img_off, null); //设置右图标
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
